#include "App_Mqtt.h"

static MQTTClient client;
static MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
static MQTTClient_message pubmsg = MQTTClient_message_initializer;
static int (*receive_callback)(char *json) = NULL;

static void delivered(void *context, MQTTClient_deliveryToken dt)
{
    log_debug("消息发送完成！");
}

static int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    int result = 0;// 默认不成功，1为成功，0为失败
    if (receive_callback != NULL)
    {
        result = receive_callback((char *)message->payload) == 0 ? 1 : 0;
    }
    // 释放内存
    MQTTClient_freeMessage(&message);
    MQTTClient_free(topicName);
    return result;
}

static void connlost(void *context, char *cause)
{
    log_error("MQTT连接断开，原因是%s", cause);
}

/**
 * @brief 初始化MQTT
 *
 */
int App_Mqtt_Init(void)
{
    // 创建MQTT客户端
    if (MQTTClient_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTT客户端创建失败！");
        MQTTClient_destroy(&client);

        return -1;
    }

    // 设置回调函数
    if (MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTT回调函数设置失败！");
        MQTTClient_destroy(&client);
        return -1;
    }

    // 连接MQTT服务器
    if (MQTTClient_connect(client, &conn_opts) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTT服务器连接失败！");
        MQTTClient_destroy(&client);
        return -1;
    }

    // 订阅主题
    if (MQTTClient_subscribe(client, TOPIC_Receive, QOS) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTT客户端订阅主题失败！");
        // 断开连接，销毁客户端
        MQTTClient_disconnect(client, TIMEOUT);
        MQTTClient_destroy(&client);
        return -1;
    }
    log_debug("MQTT初始化成功！");
    return 0;
}

/**
 * @brief 关闭MQTT的连接
 *
 */
void App_Mqtt_Close(void)
{
    // 1. 取消订阅
    MQTTClient_unsubscribe(client, TOPIC_Receive);

    // 2. 断开连接
    MQTTClient_disconnect(client, TIMEOUT);

    // 3. 销毁客户端
    MQTTClient_destroy(client);
}

/**
 * @brief 发送数据到MQTT服务器
 *
 * @param json 需要发送的数据
 * @return int 发送成功：0, 发送失败：-1
 */
int App_Mqtt_Send(char *json)
{
    pubmsg.payload = json;
    pubmsg.payloadlen = strlen(json);
    pubmsg.qos = QOS;
    if (MQTTClient_publishMessage(client, TOPIC_Send, &pubmsg, NULL) != MQTTCLIENT_SUCCESS)
    {
        log_error("消息发送失败！");
        return -1;
    }
    log_debug("消息发送成功！");

    return 0;
}

/**
 * @brief 注册MQTT接收数据的回调函数
 *
 * @param callback 处理消息的回调函数
 */
void App_Mqtt_RegisterRecvCallBack(int (*callback)(char *json))
{
    // 将传入的回调函数保存到receive_callback中
    receive_callback = callback;
}
